package org.yylnb.openplatform.gateway.mq.listener;

import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;
import org.yylnb.openplatform.commons.utlis.CommonsResult;
import org.yylnb.openplatform.gateway.api.CacheService;
import org.yylnb.openplatform.commons.bean.FunctionType;
import org.yylnb.openplatform.commons.bean.NotifyMQBean;
import org.yylnb.openplatform.commons.bean.OperatorType;
import org.yylnb.openplatform.gateway.utils.LocalCacheUtils;

import java.util.Map;

/**
 * @author RainLin
 * @date 2020/7/25 - 20:11
 */
@Component
public class NotifyListener {
    private final CacheService cacheService;

    public NotifyListener(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    @StreamListener("NoticeTheGateway")
    public void onMessage(NotifyMQBean bean) {
        System.err.println(bean);
        FunctionType functionType = bean.getFunctionType();
        OperatorType operatorType = bean.getOperatorType();
        String key = bean.getKey();

        if ((functionType == FunctionType.API_MAPPING && operatorType == OperatorType.ADD)||(functionType == FunctionType.API_MAPPING && operatorType == OperatorType.UPDATE)) {
            //添加了一个映射,从缓存中把新添加的路由信息保存到本地
            CommonsResult<Map<String,String>> beanWithObject = null;
            try {
                beanWithObject = cacheService.hGetAll(key);
            } catch (Exception e) {
                e.printStackTrace();
            }
            LocalCacheUtils.addMapping(key,beanWithObject.getData());
        }
        //TODO 将其他不同的操作进行补全
    }
}
